//
//  FQDPhotoViewerController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/1/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDPhotoViewerController.h"
#import "FQDCaptionView.h"
#import "MBProgressHUD+FQDExtension.h"
#import "UIView+FQDExtension.h"

#import "MWPhotoBrowser.h"
#import "MWZoomingScrollView.h"

@interface FQDPhotoViewerController () <MWPhotoBrowserDelegate>
// 图片数据
@property (nonatomic, strong) NSArray *photoArray;
@property (nonatomic, strong) UIView *containerView;
// 导航条
@property (nonatomic, strong) FQDPhotoViewerNavBar *navBar;
// 批注
@property (nonatomic, strong) FQDCaptionView *captionView;
// 图片浏览器
@property (nonatomic, strong) MWPhotoBrowser *photoBrowser;
@property (nonatomic, assign) NSUInteger initialIndex;
@end

@implementation FQDPhotoViewerController

#pragma mark - Initializers
- (instancetype)initWithPhotos:(NSArray *)photos currentIndex:(NSUInteger)currentIndex
{
    self = [super init];
    if (self) {
        _photoArray = photos;
        _initialIndex = currentIndex;
    }
    return self;
}

#pragma mark - View life cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIView *containerView = [[UIView alloc] initWithFrame:self.view.bounds];
    containerView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:containerView];
    self.containerView = containerView;
    
    [self setupPhotoBrowser];
    [self setupPhotoBrowserNavBar];
    [self setupPhotoBrowserCaption];
    [self setupGestureRecognizers];
    [self preparePresentAnimation];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self playPresentAnimation];
}

#pragma mark - Private methods
- (void)setupPhotoBrowserNavBar
{
    CGRect navBarFrame = CGRectMake(0, 0, self.view.bounds.size.width, 64.0f);
    self.navBar = [[FQDPhotoViewerNavBar alloc] initWithFrame:navBarFrame];
    [self.containerView addSubview:self.navBar];
    
    [self.navBar.backButton addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.navBar.downloadButton addTarget:self action:@selector(downloadImage:) forControlEvents:UIControlEventTouchUpInside];   
}

- (void)setupPhotoBrowserCaption
{
    CGFloat height = 60.0f;
    CGSize boundsSize = self.view.bounds.size;
    CGRect frame = CGRectMake(0, boundsSize.height - height, boundsSize.width, height);
    FQDCaptionView *captionView = [[FQDCaptionView alloc] initWithFrame:frame];
    [self.containerView addSubview:captionView];
    self.captionView = captionView;
}

- (void)setupPhotoBrowser
{
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.zoomPhotosToFill = NO;
    browser.displayNavArrows = NO;
    browser.displayActionButton = NO;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = YES;
    browser.enableGrid = YES;
    browser.enableSwipeToDismiss = NO;
    browser.startOnGrid = NO;
    browser.autoPlayOnAppear = NO;
    browser.view.backgroundColor = [UIColor clearColor];
    [browser setCurrentPhotoIndex:self.initialIndex];
    
    self.photoBrowser = browser;
    [self addChildViewController:browser];
    [self.containerView addSubview:browser.view];
}

- (void)setupGestureRecognizers
{
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                             action : @selector(backgroundTapped:)];
    [self.photoBrowser.view addGestureRecognizer:tapRecognizer];
}

- (MWZoomingScrollView *)currentPageInBrowser
{
    NSSet *visiblePages = [self.photoBrowser valueForKey:@"visiblePages"];
    MWZoomingScrollView *currentPage = nil;
    for (MWZoomingScrollView *page in visiblePages) {
        if (page.index == self.photoBrowser.currentIndex) {
            currentPage = page;
        }
    }
    return currentPage;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - Event Response
- (void)goBack:(id)sender
{
    [self dismissWithAnimation];
}

- (void)downloadImage:(id)sender
{
    MWPhoto *currentPhoto = [self photoBrowser:self.photoBrowser photoAtIndex:self.photoBrowser.currentIndex];
    if ([currentPhoto underlyingImage]) {
        UIImageWriteToSavedPhotosAlbum([currentPhoto underlyingImage],
                                       self,
                                       @selector(image:didFinishSavingWithError:contextInfo:),
                                       nil);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    [MBProgressHUD showMessage:(error ? @"保存图片失败" : @"保存图片成功")];
}

#pragma mark - Gesture Recognizers
- (void)backgroundTapped:(UIGestureRecognizer *)gr
{
    [self goBack:nil];
}

#pragma mark - Animation

- (void)preparePresentAnimation
{
    self.photoBrowser.view.alpha = 0;
    
}

- (void)playPresentAnimation
{
    [UIView animateWithDuration:0.20f animations:^{
        self.photoBrowser.view.alpha = 1.0f;
    } completion:nil];
    
    UIScrollView *pagingScrollView = [self.photoBrowser valueForKey:@"pagingScrollView"];
    pagingScrollView.alpha = 0;
    [UIView animateWithDuration:0.20f animations:^{
        pagingScrollView.alpha = 1.0f;
    } completion:nil];
    
}

- (void)dismissWithAnimation
{
    
    MWZoomingScrollView *currentPage = [self currentPageInBrowser];
    MWCaptionView *captionView = currentPage.captionView;
    
    CGFloat x = 0;
    CGFloat y = self.navBar.frame.size.height;
    CGFloat w = self.view.bounds.size.width;
    CGFloat h = self.view.bounds.size.height - self.navBar.frame.size.height - captionView.frame.size.height;
    CGRect visibleRect = CGRectMake(x, y, w, h);
    
    UIImageView *photoImageView = [currentPage valueForKeyPath:@"photoImageView"];
    UIView *photoSuperview = photoImageView.superview;
    
    CGRect photoRect = [self.view convertRect:photoImageView.frame fromView:photoSuperview];
    CGRect captureRect = CGRectIntersection(photoRect, visibleRect);
    CGRect clipRect = [self.photoBrowser.view convertRect:captureRect fromView:self.view];
    UIImage *captureImage = [self.photoBrowser.view captureViewAfterScreenUpdates:NO clipRect:clipRect];
    
    UIImageView *captureImageView = [[UIImageView alloc] initWithFrame:captureRect];
    captureImageView.image = captureImage;
    
    UIView *containerView = self.containerView;
    [containerView addSubview:captureImageView];
    
    self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:1.0f];
    self.photoBrowser.view.hidden = YES;
    
    [UIView animateWithDuration:0.30f delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{

        containerView.transform = CGAffineTransformMakeScale(0.01f, 0.01f);
        self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
    
    
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return [self.photoArray count];
}

- (id<MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    return self.photoArray[index];
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
{
    NSString *title = [NSString stringWithFormat:@"%@ / %@", @(index+1), @([self.photoArray count])];
    self.navBar.titleLabel.text = title;
    
    id<MWPhoto> photo = [self photoBrowser:photoBrowser photoAtIndex:index];
    self.captionView.hidden = ([[photo caption] length] <= 0);
    self.captionView.photo = photo;
}

- (MWCaptionView *)photoBrowser:(MWPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index
{
    return nil;
}

@end
